import 'package:largefriends/entity/entities/lf_bool_entity.dart';
import 'package:largefriends/net/error_handle.dart';
import 'package:largefriends/net/lf_dio_util.dart';

import '../../entity/entities/lf_user_entity.dart';
import '../manager/lf_user_cache_manager.dart';
import '../../net/lf_api_url.dart';
import 'lf_im_service.dart';

extension IMServiceMSGExt on LfIMService {
  Future<LfUserEntity?> getChatUser(String uid) async {
    var result = LfUserCacheManager().getCacheUser(key: uid);
    Map<String, dynamic> requestMap = {};
    requestMap.putIfAbsent("profId", () => uid);
    if (result == null) {
      await LfDio().get<LfUserEntity>(url: apiProfile, params: requestMap).then(
          (data) {
        result = data;
        LfUserCacheManager().setCacheUser(key: uid, user: result!);
      }, onError: (error) {
        throw error;
      });
    } else {
      ///即使不为空,也可以更新一下下的嘛
      LfDio()
          .get<List<LfUserEntity>>(url: apiChattedUsers, params: requestMap)
          .then((data) {
        if (data.isNotEmpty) {
          result = data.first;
          LfUserCacheManager().setCacheUser(key: uid, user: result!);
        }
      }, onError: (error) {});
    }
    return result;
  }

  Future<String> canChat(String uid) async {
    var result = canChatMap[uid];
    if (result == null) {
      Map<String, dynamic> requestCanChatMap = {};
      requestCanChatMap.putIfAbsent(
          'sender', () => authService.currentAccount?.userId);
      requestCanChatMap.putIfAbsent('receiver', () => uid);
      await LfDio()
          .get<LfBoolEntity>(url: apiChatCanChat, params: requestCanChatMap)
          .then((data) {
        if (data.ret == true) {
          canChatMap[uid] = "true";
        } else {
          canChatMap[uid] = 'false';
        }
      }, onError: (error) {
        if (error is NetError) {
          if (codeBlockedMe == error.code || codeBlockMeCode == error.code) {
            canChatMap[uid] = error.msg;
          } else if (error.code == codeBlocked) {
            canChatMap[uid] = error.msg;
          } else if (error.code == 30003010) {
            canChatMap[uid] = "false";
          }
        }
      });
    }
    return canChatMap[uid] ?? 'true';
  }
}
